/*
 * @(#)EncodingService.java 2011
 *
 *
 * Copyright 2011 classic-commerce
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package ca.ioniq.server.service.security;

import java.io.IOException;
import java.security.SecureRandom;

import org.jasypt.digest.config.SimpleDigesterConfig;
import org.jasypt.salt.FixedByteArraySaltGenerator;
import org.jasypt.util.password.ConfigurablePasswordEncryptor;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import ca.ioniq.shared.entity.Credential;

public class EncodingService {
	
    private static final int SALT_LENGTH = 8;
	ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
	SimpleDigesterConfig simpleDigesterConfig = new SimpleDigesterConfig();
	FixedByteArraySaltGenerator saltGenerator = new FixedByteArraySaltGenerator();
 
    public EncodingService() {
    	configureEncoder();
    }
    
	public void configureEncoder() {
		
        passwordEncryptor.setAlgorithm("SHA-256");
        passwordEncryptor.setPlainDigest(true);
        
        passwordEncryptor.setConfig(simpleDigesterConfig);
        simpleDigesterConfig.setSaltGenerator(saltGenerator);
	}

    public String encodePassord(String clearPassword, byte[] salt) {
    	saltGenerator.setSalt(salt);
    	
    	return passwordEncryptor.encryptPassword(clearPassword);
    }

	public Credential getCredentialFromClearPassword(String clearPassword) {
		byte[] seed = SecureRandom.getSeed(SALT_LENGTH);
		
		Credential credential = new Credential();
		credential.setSalt(new BASE64Encoder().encode((seed)));
		credential.setPassword(encodePassord(clearPassword, seed));

		return credential;
	}
    
	public boolean verifyPassword(String plainPassword, Credential credential) throws IOException {
		
		saltGenerator.setSalt(new BASE64Decoder().decodeBuffer(credential.getSalt()));
		
		return passwordEncryptor.checkPassword(plainPassword, credential.getPassword());
	}
}
